import React, { MouseEvent } from "react";
import { useDispatch } from "react-redux";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import useGetPageInfo from "../../../hooks/useGetPageInfo"; // 添加引入
import {
  moveComponent,
  changeSelectedId,
  ComponentInfoType,
} from "../../../store/componentsReducer";
import { getComponentConfByType } from "../../components/QuestionComponents";
import styles from "./EditCanvas.module.scss";
import classNames from "classnames";
import useBindCanvasKeyPress from "../../../hooks/useBindCanvasKeyPress";
import SortableContainer from "../../components/DragSortable/SortableContainer";
import SortableItem from "../../components/DragSortable/SortableItem";

function genComponent(componentInfo: ComponentInfoType) {
  const { type, props } = componentInfo;
  const componentConf = getComponentConfByType(type);

  if (componentConf === null) return null;
  const { Component } = componentConf;

  return <Component {...props} />;
}

const EditCanvas: React.FC = () => {
  const { componentList, selectedId } = useGetComponentInfo();
  const { isPublished } = useGetPageInfo();
  const dispatch = useDispatch();

  useBindCanvasKeyPress();

  function handleClick(event: MouseEvent, id: string) {
    // 当问卷已发布时，禁用点击选择功能
    if (isPublished) return;

    event.stopPropagation();
    if (selectedId === id) return dispatch(changeSelectedId(""));
    dispatch(changeSelectedId(id));
  }

  function handleDragEnd(oldIndex: number, newIndex: number) {
    // 当问卷已发布时，禁用拖拽功能
    if (isPublished) return;

    dispatch(moveComponent({ oldIndex, newIndex }));
  }

  return (
    <div className={styles.canvas}>
      <SortableContainer items={componentList} onDragEnd={handleDragEnd}>
        {componentList
          .filter((c) => !c.isHidden)
          .map((c) => {
            const { id, isLocked } = c;
            const wrapperDefaultClassName = styles["component-wrapper"];
            const selectedClassName = styles.selected;
            const hoverClassName = styles.hover;
            const disabledClassName = styles.disabled;
            const wrapperClassName = classNames({
              [wrapperDefaultClassName]: true,
              [selectedClassName]: selectedId === id,
              [hoverClassName]: !isPublished, // 已发布时，禁用hover
              [disabledClassName]: isLocked || isPublished, // 锁定或已发布时，添加禁用样式
            });

            return (
              <SortableItem key={id} id={id}>
                <div
                  className={wrapperClassName}
                  onClick={(e) => handleClick(e, id)}
                >
                  <div className={styles.component}>{genComponent(c)}</div>
                </div>
              </SortableItem>
            );
          })}
      </SortableContainer>
    </div>
  );
};

export default EditCanvas;
